<template>
	<u-popup mode="center" :show="visible" @close="close" :round="10" :safeAreaInsetTop="true">
		<view class="picker-box" :style="{maxHeight:maxHeight+'px'}">
			<view class="picker-item auto-wrap" v-for="(item,index) in list" :key="'picker-item-'+index" @tap.stop="onItemClick(index,item)">
				{{(typeof(item)==='string'||typeof(item)==='number'||typeof(item)==='boolean'||item===null)?item:item[labelField]}}
			</view>
		</view>
	</u-popup>
</template>

<script>
export default {
	name:'easyPickerCompontent',
	emits:['update:visible','select'],
	props:{
		visible:{
			type:Boolean,
			default:false
		},
		list:{
			type:Array,
			default:function(){
				return []
			}
		},
		valueField:{
			type:String,
			default:'value'
		},
		labelField:{
			type:String,
			default:'label'
		}
	},
	data(){
		return {
			maxHeight:500
		}
	},
	methods:{
		close(){
			this.$emit('update:visible',false)
		},
		onItemClick(index,selection){
			let valObj = selection;
			let val;
			if (typeof selection === 'string' || typeof selection === 'number'||typeof(selection)==='boolean'||selection===null) {
				val = selection;
			} else {
				try{
					val = selection[this.valueField];
				}catch(e){
					val = selection;
				}
			}
			this.close()
			this.$emit('select',val,valObj,index)
		}
	}
}
</script>

<style scoped lang="scss">
.picker-box{
	width: 90vw;
	background-color: #fff;
	border-radius: 20rpx;
	padding: 30rpx 0;
	overflow: auto;
	.picker-item{
		margin: 0 20rpx 30rpx 20rpx;
		text-align: center;
		background-image: linear-gradient(to right, $color-paimary-darken, $color-paimary-lighten);
		border: 1px solid #e4e4e4;
		border-radius: 10rpx;
		padding: 20rpx;
		&:last-child{
			margin-bottom: 0;
		}
	}
}
</style>